﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Casamiel.API.Infrastructure;
using Casamiel.API.Infrastructure.Filters;
using Casamiel.Application;
using Casamiel.Application.Commands;
using Casamiel.Application.Commands.Waimai;
using Casamiel.Common;
using Casamiel.Domain.Request.Waimai;
using Casamiel.Domain.Response;
using Casamiel.Domain.Response.Waimai;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Casamiel.API.Controllers.V1.WaiMai
{
    /// <summary>
    /// waimai发票
    /// </summary>
    [ApiVersion("1.0")]
    [Route("api/v{api-version:apiVersion}/WaiMai/[controller]")]
    [ApiController]
    [Authorize]
    [TypeFilterAttribute(typeof(CheckTokenAttribute))]
    public class InvoiceController : BaseController
    {
        private readonly NLog.ILogger logger = NLog.LogManager.GetLogger("WaimaiService");
        private readonly IMediator _mediator;
        private readonly IOrderService _orderService;
      
        /// <summary>
        /// 
        /// </summary>
        /// <param name="mediator"></param>
        /// <param name="orderService"></param>
        public InvoiceController(IMediator mediator, IOrderService   orderService)
        {
            _mediator = mediator;
            _orderService = orderService;
        }
        /// <summary>
        /// 保存开票信息
        /// </summary>
        /// <param name="req"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> Save([FromBody] InvoiceSaveReq req, [FromHeader(Name = "u-token")] string token)
        {
            if (req == null)
            {
                throw new ArgumentNullException(nameof(req));
            }

            var mobile =  MemberHelper.GetMobile(token);
            var cmd = new SaveInvoiceInfoCommand
            {
                Mobile=mobile,
                Address = req.Address,
                Type =req.Type ,
                InvoiceTitle = req.InvoiceTitle,
                TaxpayerId = req.TaxpayerId,
                EMail = req.EMail,
                InvoiceId = req.InvoiceId,
                OpeningBank = req.OpeningBank,
                Phone = req.Phone
            };
            var result = await _mediator.Send(cmd).ConfigureAwait(false);
            return Ok(result);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<BaseResult<List<InvoiceBaseRsp>>> GetMyInoviceInfo([FromHeader(Name = "u-token")] string token)
        {
            var mobile = MemberHelper.GetMobile(token);
            var cmd = new GetMyInvoiceInfoCommand { Mobile = mobile };
            var result = await _mediator.Send(cmd).ConfigureAwait(false);
            return result;
        }

        /// <summary>
        /// 订单补开票
        /// </summary>
        /// <param name="req"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<BaseResult<string>> OrderInvoice(OrderInvoiceRequest req,[FromHeader(Name = "u-token")] string token)
        {
            if (req == null)
            {
                throw new ArgumentNullException(nameof(req));
            }

            var mobile = MemberHelper.GetMobile(token);
            var cmd = new OrderInvoiceCommand(mobile, req.OrderCode, req.InvoiceId,LoginInfo.Item3);
            var result = await _mediator.Send(cmd).ConfigureAwait(false);
            if (result.Code == 0)
            {
                var entity = await _orderService.GetByOrderCodeAsync<ICasaMielSession>(req.OrderCode).ConfigureAwait(false);
                //var d = new GetOrderDetailCommand(req.OrderCode, mobile);
                //var rsp = await _mediator.Send(d).ConfigureAwait(false);
                if (entity!=null && entity.OrderStatus==(int)OrderStatus.Completed)
                {
                    var cmd1 = new InvoiceOpeningByTradeNOCommand { TradeNO = entity.IcTradeNO};
                    var rsp1 = await _mediator.Send(cmd1).ConfigureAwait(false);
                    logger.Trace($"开票:{ entity.IcTradeNO},{rsp1}");
                }
                else
                {
                    logger.Error($"开票出错{ entity.IcTradeNO}");
                }   
            }
                
            return result;
        }

    }
}
